package com.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wms.entity.Admin;
import com.wms.entity.AdminRole;
import com.wms.entity.MyPage;
import com.wms.entity.Role;
import com.wms.mapper.AdminMapper;
import com.wms.service.AdminRoleService;
import com.wms.service.AdminService;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminServiceImpl extends BaseServiceImpl<AdminMapper, Admin> implements AdminService {

    @Resource
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleService adminRoleService;

    @Override
    public Admin findByUsername(String username) {
        if (StringUtils.isEmpty(username)) return null;
        return adminMapper.findByUsername(username);
    }

    @Override
    @Transactional
    public void bindRole(Admin admin, Role role) {
        Assert.notNull(role);
        Assert.notNull(admin);

        UpdateWrapper<AdminRole> wrapper = new UpdateWrapper<AdminRole>();
        wrapper.eq("admin_id", admin.getId());
        adminRoleService.remove(wrapper);

        AdminRole adminRole = new AdminRole();
        adminRole.setRoleId(role.getId());
        adminRole.setAdminId(admin.getId());
        adminRoleService.save(adminRole);
    }

    @Override
    public void queryRolePage(MyPage<Admin> page) {
        queryPage("queryRolePage", page);
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        Assert.notNull(id);

        removeById(id);
        adminRoleService.deleteByAdminId(id);
    }

    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
        Assert.notEmpty(ids);

        removeByIds(ids);
        adminRoleService.deleteByAdminIds(ids);
    }
}
